# Pdf Reader Locator

import Tms
import os, wx

def FindPdfAssociation(self, Options):
    #find the location of Adobe Pdf reader
    if Options['OS'] == 'win32':
        import _winreg as reg
        #Try to find PDF Reader
        try:
            keyReg = reg.ConnectRegistry(None, reg.HKEY_CLASSES_ROOT)
            keyPdf = reg.OpenKey(keyReg, '.pdf')
            keyPdfValue = reg.QueryValue(keyPdf, '')
            keyPdf2 = reg.OpenKey(keyReg, keyPdfValue)
            keyShell = reg.OpenKey(keyPdf2, 'Shell')
            keyOpen = reg.OpenKey(keyShell, 'Open')
            keyCommand = reg.OpenKey(keyOpen, 'Command')
            pdfReaderLocation = reg.QueryValue(keyCommand, '')
            pdfReaderLocation = pdfReaderLocation.split('" "')[0].strip('"')
            if os.path.exists(pdfReaderLocation):
                Options['Pdf Reader'] = pdfReaderLocation
            else:
                BrowseForPdfReader(self)
        
        except:
            #error with finding key so browse for it
            BrowseForPdfReader(self, Options)
        
    
def BrowseForPdfReader(self, Options):
    #popup browser for pdf reader
    dlg = wx.MessageDialog(self, 'A PDF Reader is necessary to view and print reports. Press "Yes" to browse for the file, or Press "No" to continue without a PDF Reader',
                           'No PDF Reader Selected',
                           wx.YES_NO | wx.ICON_HAND
                           #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                           )
    ans = dlg.ShowModal()
    dlg.Destroy()
    if ans == wx.ID_YES:
        #pop up dirdialog to find file
        PdfReaderDialog(self, Options)
    else:
        #no selected, so store
        Options['Pdf Reader'] = ''
    
def PdfReaderDialog(self, Options):
    fileDlg = wx.FileDialog(self, 'Select a PDF Reader', style= wx.FD_OPEN)
    if fileDlg.ShowModal() == wx.ID_OK:
        pdfReaderLocation = fileDlg.GetPath()
        Options['Pdf Reader'] = pdfReaderLocation
    else:
        Options['Pdf Reader'] = ''
    fileDlg.Destroy()

if __name__ == '__main__':
    Tms.Main()
